package com.baton.plugins.finder;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

@WebServlet("/btfinder.java")
public class FinderServlet extends HttpServlet{


	/**
	 * 
	 */
	private static final long serialVersionUID = -2783049069901745403L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		getResponse(request, response);
	}


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		System.out.println("command++>" + command);
		postResponse(request, response);
	}

	private void postResponse(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String command = request.getParameter("command");
		
//		if("FileUpload".equals(command)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();  
            factory.setSizeThreshold(5*1024); //最大缓存    
//            factory.setRepository(new File(serverPath+tempPath));//临时文件目录    
            ServletFileUpload upload = new ServletFileUpload(factory);  
            upload.setSizeMax(10*1024*1024);//文件最大上限 
            
            try {
				List<FileItem> items = upload.parseRequest(request);//获取所有文件列表    
				for (FileItem item : items) {
					System.out.println("item=" + item.getName());
					if(!item.isFormField()){
						//文件名    
                        String fileName = item.getName().toLowerCase();
						System.out.println("fileName-->" + fileName);
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//		}
	}


	@Override
	public void init() throws ServletException {
		ServletContextFactory.setServletContext(getServletContext());
	}
	
	/**
	 * get res
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void getResponse(HttpServletRequest request, HttpServletResponse response) 
			throws IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String command = request.getParameter("command");
		String basePath =  getServletContext().getRealPath("/userfiles/grandid/userid");
		if("init".equals(command)) {
			File base = new File(basePath);
			File[] list = base.listFiles();
			List<Map<String, String>> filesList = new ArrayList<Map<String,String>>();
			filesTree(filesList, list, "");
			out.println(JSON.toJSONString(filesList));
		} else if("getFiles".equals(command)){
			String id = request.getParameter("id");
			id = URLDecoder.decode(id, "UTF-8").replaceAll("\\\\", "/");
			String path = getServletContext().getRealPath("/userfiles/grandid/userid"+id);
			HttpSession session = request.getSession();
			session.setAttribute("basePath", "grandid/userid");
			session.setAttribute("path", id);
			File file = new File(path);
			File[] files = file.listFiles();
			List<Map<String, Object>> filesList = new ArrayList<Map<String,Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
			for(File f : files){
				if(f.isFile()){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("name", f.getName());
				map.put("size", f.length());
				map.put("creatTime", sdf.format(new Date(f.lastModified())));
				filesList.add(map);
				}
			}
			
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("path", id);
			maps.put("url", "/userfiles/grandid/userid"+id);
			maps.put("file", filesList);
			System.out.println(JSON.toJSONString(maps));
			out.println(JSON.toJSONString(maps));
		}
	}

			
			
	
	private int filesTree(List<Map<String, String>> filesList, File[] files, String root) {
		int dirCount = 0;
		if(files != null && files.length > 0) {
			for(File f : files) {
				if(!f.isFile()) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("id", root + File.separator + f.getName());
					map.put("pId", root);
					map.put("name", f.getName());
					filesList.add(map);
					if(f.isDirectory()) {
						dirCount++;
						File[] list = f.listFiles();
						if(list != null && list.length > 0) {
							if(filesTree(filesList, list, map.get("id")) == 0) {
								map.put("iconSkin", "diy01");
							}
						} else {
							map.put("iconSkin", "diy01");
						}
					}
				}
			}
		}
		return dirCount;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
